﻿using AutoMapper.Execution;
using MediatR;
using T_Person.BaseRep.Interface;
using T_Person.Read.APi.Applaction.Command.TotalPersonnel;
using T_Person.Read.APi.Dto;

namespace T_Person.Read.APi.Applaction.CommandHandlers.TotalPersonnelHandlers
{
    public class TotalAgeEmployeementHandlers : IRequestHandler<TotalAgeEmployeeCommand, List<PersonnelAgeGroup>>
    {
        private readonly IEmployeeRep employeeRep;

        public TotalAgeEmployeementHandlers(IEmployeeRep employeeRep)
        {
            this.employeeRep = employeeRep;
        }

        public async Task<List<PersonnelAgeGroup>> Handle(TotalAgeEmployeeCommand request, CancellationToken cancellationToken)
        {
            var list = await employeeRep.GetvaluesByResult(x => !x.IsDel);
            int listcount = list.Count();
            var totallist = list.ToArray().GroupBy(x =>
            {
                var age = CalculateAge(x.Ebirthday);
                if (24 >= age && age >= 18) return "18-24岁之间";
                if (29 >= age && age >= 25) return "29-25岁之间";
                if (39 >= age && age >= 30) return "39-30岁之间";
                if (49 >= age && age >= 40) return "49-40岁之间";
                return "50岁以上"; // 41岁及以上  
            }).Select(x => new PersonnelAgeGroup
            {
                name = x.Key,
                number = Math.Round(((double)x.Count()) / listcount * 100, 2)
            }) ;
            var lists = totallist.ToList();
            return lists; 
        }

        public  int CalculateAge(DateTime? birthDate)
        {
            DateTime dateTime = Convert.ToDateTime(birthDate);
            if (dateTime > DateTime.Now)
            {
                throw new ArgumentException("Birth date can't be in the future.");
            }
            
            int age = DateTime.Now.Year - dateTime.Year;

            // 如果当前日期在生日之前，那么实际年龄应该少一岁  
            if (DateTime.Now.Month < dateTime.Month ||
                (DateTime.Now.Month == dateTime.Month && DateTime.Now.Day < dateTime.Day))
            {
                age--;
            }

            return age;
        }
    }
}
